/* DemoController2.java

{{IS_NOTE
 Purpose:
  
 Description:
  
 History:
  May 13, 2011 3:00:08 PM , Created by simonpai
}}IS_NOTE

Copyright (C) 2011 Potix Corporation. All Rights Reserved.

{{IS_RIGHT
}}IS_RIGHT
*/
package demo.web.ui.ctrl;

import java.util.Set;

import javax.validation.ConstraintViolation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import demo.web.ui.ctrl.Validations.ViolationRunner;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.BindingValidateEvent;
import org.zkoss.zul.Label;
import demo.model.bean.User;

/**
 * A more customized example of Bean Validation
 * @author   simonpai
 */
public class DemoController2 extends GenericForwardComposer {
	
	private static final long serialVersionUID = 2365609737947623977L;
	
	private final Logger _logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * @uml.property  name="_user"
	 * @uml.associationEnd  
	 */
	private User _user = User.getUser();
	
	// getter //
	public User getUser() {
		return _user;
	}
	
	// event handler //
	public void onBindingValidate$submit(BindingValidateEvent event) {
		
		Validations.validate(event, new ViolationRunner(){
			public void run(Set<ConstraintViolation<?>> violations, Object bean, Component ref) {
				
				// set or clear error labels
				Component nref = ref.getNextSibling();
				if(nref instanceof Label)
					((Label) nref).setValue(violations.isEmpty() ? 
							"" : violations.iterator().next().getMessage());
				
				// may also log here
				for(ConstraintViolation<?> v : violations)
					_logger.info("[Bean Constraint Violation] " + bean.getClass() + 
							": " + v.getPropertyPath() + ": " + v.getMessage()); 
			}
		});
		
		_logger.info("Data saved to user: " + _user.getFullDesc());
	}
	
}
